<?php
	//开启session
	Session_start();
	//引入配置文件
	include('../public/config.php');
	//连接数据库
	$con=@mysql_connect(HOST,USER,PASS) or die('数据库连接失败！');
	//选择数据库并设置字符集
	mysql_select_db(DBNAME,$con);
	mysql_set_charset('utf8');
	switch($_GET['a']){
		case "doLogin":
		//会员登录
		//接收值
		$username=$_POST['username'];
		$pass=$_GET['pass'];
		//编写sql语句
		$sql="select pass,state,id from users where username='{$username}'";
		//执行sql语句
		$result=mysql_query($sql);
		//遍历结果集并判断是账号、密码是否正确
		if(mysql_num_rows($result)>0){
			//执行sql语句
				$user = mysql_fetch_assoc($result);
			//判断状态是否为可登录
				if($user['state']==2){
					echo "<script>alert('该用户已被禁用！');window.location.href='./login.php';</script>";
					exit;
				}
			//判断密码是否相同
			if(md5($user['pass']) == md5($_POST['pass'])){
			//将成功登录的用户信息写入session
				$_SESSION['user']=$username;
			//登录成功！
				header('Location:index.php');
			}else{
			//登录失败，密码错误！
				echo "<script>alert('账号或密码不输入错误！');window.location.href='login.php';";
				exit;
			}
		}else{
			//登录失败,用户不存在！
			echo "<script>alert('此用户不存在！！');window.location.href='./login.php';</script>";
			exit;
		}
		break;
		case 'register':
			$pass=$_POST['pass'];
			$repass=$_POST['repass'];
			$phone=$_POST['phone'];
			$username=$_POST['username'];
			$code=$_POST['code'];
			$name=$_POST['name'];
			$addtime=time();
			$state=3;
			//进行判断
			//校验验证码
				if($code != $_SESSION['code']){
					echo "<script>alert('验证码错误！');window.location.href='./register.php';</script>";
					exit;
				}
			//判断两输入的密码是否一致
				if($pass !== $repass){
					echo "<script>alert('两次密码输入不一致！');window.location.href='./register.php';</script>";
					exit;
				}
			//判断用户名是否已经存在
			$namesql="select username from users";
			$nameresult=mysql_query($namesql);
			while($row=mysql_fetch_assoc($nameresult)){
				//var_dump($row);
				if(in_array($username,$row)){
					echo "<script>alert('该用户已经存在，请重新输入');window.location.href='./register.php';</script>";
					exit;
				}
			}
			//将用户信息写入数据库并写入session
			$mysql = "insert into users(username,name,phone,pass,state,addtime) values('{$username}','{$name}',{$phone},'{$pass}',{$state},{$addtime})";
			mysql_query($mysql);
			//判断插入操作是否执行成功
				if(mysql_insert_id($con)>0){
					header('location:./index.php');
					$_SESSION['user']=array($username,$pass);
				}
			break;
			
			
		case 'delshop':
			$id=$_GET['id'];
			$arr=array_flip(($_SESSION['shop']));
			
			if(in_array($id,$arr)){
				unset($_SESSION['shop'][$id]);
				header('location:./cart.php');
			}
			break;
			
			
		//关闭数据库
		mysql_close($link);
		case 'doLogout':
			unset($_SESSION['user']);
			if(u!=0){
			header('Location:index.php');
			}else{
			header('Location:login.php');
			}
			break;		
	}